﻿/*
 * Created by SharpDevelop.
 * User: Михаил
 * Date: 28.07.2013
 * Time: 14:56
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;
namespace Region.Utils
{
    public class Find
    {
        static Int32 PoleN = 0;
        List<String> m_Words;
        String[] m_Ends;
        //String m_Find;
        Dictionary<String, String> ReplaseString;
        public void readString(String str)
        {
          
            // Развернуть сокращения
            String S1 = str;
            foreach (KeyValuePair<String, String> R in ReplaseString) S1 = Regex.Replace(S1, R.Key, R.Value, RegexOptions.IgnoreCase);
            //Удалить неиспользуемые символы
            String S2 = S1.ToLower();
            String AllowChar = "йцукенгшщзхъфывапролджэячсмитьбю1234567890qwertyuiopasdfghjklzxcvbnm";
            String S3 = "";
            foreach (char c in S2) S3 += (AllowChar.IndexOf(c) == -1) ? ' ' : c;
            // Разделить на слова
            String[] W1 = Regex.Split(S3, @"\s+");
            m_Words = new List<string>();
            foreach (String Word in W1)
                if (Word != "")
                {
                    m_Words.Add(Word);
                    m_Words.Add(" " + Word);
                    foreach (String Ends in m_Ends)
                        if (Word.EndsWith(Ends))
                        {
                            m_Words.Add(Word.Remove(Word.Length - Ends.Length));
                            m_Words.Add(" " + Word.Remove(Word.Length - Ends.Length));
                            break;
                        }
                }
        }        
        public bool forMSSQLWhere(String PoleName, out String SQL, ref Dictionary<String, Object> Param)
        {
            if (Param == null) Param = new Dictionary<String, Object>();
            String sql = "";
            foreach (String Word in m_Words)
                if (Word.Length >= 2)
                {
                    if (sql != "") sql += " OR ";
                    sql += "(" + PoleName + " LIKE " + " @Find" + PoleN.ToString() + ")";
                    Param["@Find" + PoleN.ToString()] = "%" + Word + "%";
                    PoleN++;
                }
            SQL = "(" + sql + ")";
            return true;
        }
        public bool forMSSQLOrderBy(String PoleName, out String SQL, ref Dictionary<String, Object> Param)
        {
            if (Param == null) Param = new Dictionary<String, Object>();
            String sql = "0";
            foreach (String Word in m_Words)
            {
                Int32 VP = 3;
                Int32 VM = -1;

                if (Word.Length <= 2) { VP = 1; VM = 0; }//Корректировка поиска для предлогов
                sql += "+(SELECT CASE WHEN (" + PoleName + " LIKE " + " @Find" + PoleN.ToString() + ") THEN " + VP.ToString() + " ELSE " + VM.ToString() + " END)";
                Param["@Find" + PoleN.ToString()] = "%" + Word + "%";
                PoleN++;
            }
            SQL = "(" + sql + ")";
            return true;
        }
        public Find(String str)
        {
            ReplaseString = new Dictionary<String, String>(){
                {@"ё","е"},
                {@"\bОАО\b","Открытое акционерное общество"},
                {@"\bООО\b","Общество с ограниченной ответственностью"},
                {@"\bИП\b","Индивидуальный предприниматель"}};
            m_Ends = new String[] {                 
                "ми","ый","ий","ой","ое","ее","ого","его","ому","ему","ым","им","ом","ем","ей","ою","ею","ую","юю",// Прилогательные
                "а", "я","ы","у","ю","е","ь","и", "ы", // Существительные
            };
            readString(str);
        }
    }
}
